package company.xiechen_F;

import java.util.*;

public class Xi2 {
    static long max;

    public static void main(String args[]) {
        Scanner cin = new Scanner(System.in);
        while (cin.hasNext()) {
            WorkflowNode node = WorkflowNode.load(cin.next());
            if (WorkflowNode.isWrong)
                System.out.println(-1);
            else {
                max = 0;
                helper(node, 0);
                System.out.println(max);
            }
            WorkflowNode.isWrong = false;
        }
    }

    private static void helper(WorkflowNode node, long min) {
        if (node == null)
            max = Math.max(min, max);
        else {
            List<WorkflowNode> nextNodes = node.nextNodes;
            if (nextNodes != null) {
                for (WorkflowNode w : nextNodes) {
                    if (w.initialised)
                        helper(w, min + node.timeoutMillis);
                }
            }
        }
    }
}

class WorkflowNode {
    String nodeId;
    int timeoutMillis;
    List<WorkflowNode> nextNodes;
    boolean initialised;

    static boolean isWrong = false;

    public static WorkflowNode load(String value) {
        // Create head node;
        Map<String, WorkflowNode> map = new HashMap<>();
        if (!value.contains("HEAD")) {
            isWrong = false;
            return null;
        }
        WorkflowNode head = new WorkflowNode("HEAD", 0, null);
        map.put(head.nodeId, head);

        for (String nodeValue : value.split("\\|")) {
            String[] properties = nodeValue.split("\\`");
            if (properties.length != 3) {
                isWrong = false;
                return null;
            }
            WorkflowNode node = map.get(properties[0]);

            node.timeoutMillis = Integer.parseInt(properties[1]);
            node.initialised = true;

            // Check next nodes
            if (properties[2].equals("END")) {
                continue;
            }
            if (properties[2].equals(""))
                node.nextNodes = null;
            else {
                String[] split = properties[2].split(",");
                List<WorkflowNode> list = new ArrayList<>();
                for (String s : split) {
                    WorkflowNode p = new WorkflowNode(s, 0, null);
                    list.add(p);
                    map.put(p.nodeId, p);
                }
                node.nextNodes = list;
                map.put(node.nodeId, node);
            }
        }

        return head;
    }

    public WorkflowNode(String nodeId, int timeoutMillis, List<WorkflowNode> nextNodes) {
        this.nodeId = nodeId;
        this.timeoutMillis = timeoutMillis;
        this.nextNodes = nextNodes;
    }
}
